<?php

namespace console\controllers;

use Yii;
use yii\db\Query;
use common\components\Myhelpers;
use common\models;
use yii\helpers\ArrayHelper;


class StastOrderController extends CController
{
	public $enableCsrfValidation = false;  //必须加上此选项

	public function actionIndex($date='')
    {
        $db = Yii::$app->db;

    	//没有传递date参数，即为每日统计
        if ($date == ''){
            //获取前一天  24点时间
            $day  = date('Y-m-d',strtotime('-1 day'));
            $date = $day.' 23:59:59';
        }else {
            if(!$this->checkDatetime($date)){
                echo 'erro date'."\n";
                return 1;
            }
            $day  = date('Y-m-d',strtotime($date));
            $date = $date.' 23:59:59';
        }

        //订单总量
        $sql = "SELECT COUNT(`id`) FROM `order` WHERE create_time <='$date'";
        $order_num = Yii::$app->db->createCommand($sql)->queryScalar();

        //已支付
        $sql = "SELECT COUNT(`id`) FROM `order` WHERE `order_status` IN (2,3,4) AND create_time <='$date'";
        $order_pay_num = Yii::$app->db->createCommand($sql)->queryScalar();

        //支付人数(已支付)
        $sql = "SELECT COUNT(DISTINCT `user_id`) FROM `order` WHERE `order_status` IN (2,3,4) AND create_time <='$date'";
        $order_pay_user = Yii::$app->db->createCommand($sql)->queryScalar();

        //查询当日是否已经有统计数据
        $sql = "SELECT COUNT(*) FROM `stast_order` WHERE `day` = '$day'";
        $stast_day = $db->createCommand($sql)->queryScalar();

        $time = date('Y-m-d H:i:s');

        if ($stast_day) {

            $sql = "UPDATE stast_order  SET `day`='$day', `order_num`='$order_num',`order_pay_num`='$order_pay_num',`order_pay_user`='$order_pay_user', `update_time`='$time' WHERE `day`='$day'";

            echo $sql."\n";
            $db->createCommand($sql)->execute();

        } else {

            $sql = "INSERT INTO stast_order SET `day`='$day', `order_num`='$order_num',`order_pay_num`='$order_pay_num',`order_pay_user`='$order_pay_user',`create_time`='$time'";

            echo $sql."\n";
            $db->createCommand($sql)->execute();

        }

        echo $day." stast day\n";
        return 0;
    }


    function checkDatetime($str, $format="Y-m-d H:i:s",$format1="Y-m-d"){
        $unixTime=strtotime($str);
        $checkDate= date($format, $unixTime);
        $checkDate2=date($format1, $unixTime);
        if($checkDate==$str || $checkDate2==$str)
            return 1;
        else
            return 0;
    }
}	